import React, {PureComponent} from 'react';
import {findDOMNode} from 'react-dom';
import moment from 'moment';
import {connect} from 'dva';
import {
    List,
    Card,
    Input,
    Progress,
    Button,
    Icon,
    Dropdown,
    Menu,
    Avatar,
    Modal,
    Form,
    DatePicker,
    Select,
} from 'antd';
import Link from 'umi/link';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import config from "@/config";
import styles from './TaskList.less';

const FormItem = Form.Item;
const SelectOption = Select.Option;
const {Search, TextArea} = Input;
const formLayout = {
    labelCol: {span: 7},
    wrapperCol: {span: 13},
};

@connect(({task, loading}) => ({
    task,
    loading: loading.models.task,
}))
@Form.create()
class TaskList extends PureComponent {
    state = {
        questionContentList: [{id: null, questionContent: ""}],
        visible: false,
        done: false,
        msg: ""
    };


    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'task/fetch',
        });
    }

    //分页
    handleChangePage = (page) => {
        console.log("分页")
        const {dispatch} = this.props;
        const params = {
            currentPage: page,
        };
        dispatch({
            type: 'task/fetch',
            payload: params
        });
    };

    showModal = () => {
        this.setState({
            questionContentList: [{id: null, questionContent: ""}],
            visible: true,
            current: undefined,
        });
    };

    showEditModal = item => {
        console.log("showEditModal")
        console.log(item)
        const {dispatch} = this.props;
        dispatch({
            type: 'task/getDetails',
            payload: item.id,
            callback: res => {
                if (res.result) {
                    let data = [{id: null, questionContent: ""}];
                    if(res.result.questionContentList != undefined && res.result.questionContentList != null){
                        data = res.result.questionContentList;
                    }
                    this.setState({
                        questionContentList: data,
                        visible: true,
                        current: res.result,
                    });
                }
            }
        });
        this.setState({
            questionContentList: [{id: null, questionContent: ""}],
            visible: true,
            current: item,
        });
    };

    handleDone = () => {
        const {dispatch} = this.props;
        setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            msg: "",
            done: false,
            visible: false,
        });
        dispatch({
            type: 'task/fetch',
        });
    };

    handleCancel = () => {
        setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            visible: false,
        });
    };

    handleSubmit = e => {
        console.log("提交信息")
        e.preventDefault();
        const {dispatch, form} = this.props;
        const {current,questionContentList} = this.state;
        let id,path;
        if(current){
            id = current.id;
            path = 'task/update';
        }else {
            id = null;
            path = 'task/add';
        }
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const {keys,questionContent,beginDate,endDate, ...formValue} = fieldsValue
            const data = {id,questionContentList,beginDate: moment(beginDate).format('YYYY-MM-DD HH:mm:ss'),endDate: moment(endDate).format('YYYY-MM-DD HH:mm:ss'), ...formValue}
            dispatch({
                type: path,
                payload: data,
                callback: res => {
                    this.setState({
                        done: true,
                        msg: res.msg,
                    });
                }
            });
        });
    };

    handleInitProblems = (e) => {
        e.preventDefault();
        const questionContentList = [{id: null, questionContent: ""}];
        this.setState({questionContentList: questionContentList});
    }

    handleAddProblems = (e) => {
        e.preventDefault();
        const questionContentList = [...this.state.questionContentList, {id: null, questionContent: ""}];
        this.setState({questionContentList: questionContentList});
    }

    handleProblemChange = (e,index) => {
        const data = this.state.questionContentList;
        data[index].questionContent = e.target.value
        this.setState({questionContentList: data});
    }

    deleteItem = id => {
        const {dispatch} = this.props;
        dispatch({
            type: 'list/submit',
            payload: {id},
        });
    };

    render() {
        const {
            form: {getFieldDecorator, getFieldValue},
            loading,
        } = this.props;
        const {list, pagination} = this.props.task.taskData;
        const {visible, done, questionContentList, current = {}} = this.state;
        const editAndDelete = (key, currentItem) => {
            if (key === 'edit') this.showEditModal(currentItem);
            else if (key === 'delete') {
                Modal.confirm({
                    title: '删除话题',
                    content: '确定删除该话题吗？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => this.deleteItem(currentItem.id),
                });
            }
        };

        const modalFooter = done
            ? {footer: null, onCancel: this.handleDone}
            : {okText: '提交', onOk: this.handleSubmit, onCancel: this.handleCancel};

        const Info = ({title, value, bordered}) => (
            <div className={styles.headerInfo}>
                <span>{title}</span>
                <p>{value}</p>
                {bordered && <em/>}
            </div>
        );

        const extraContent = (
            <div className={styles.extraContent}>
                <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={() => ({})}/>
            </div>
        );


        const ListContent = ({data: {beginDate, endDate, status}}) => (
            <div className={styles.listContent}>
                <div className={styles.listContentItem}>
                    <span>开始时间</span>
                    <p>{moment(beginDate).format('YYYY-MM-DD HH:mm')}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>截止时间</span>
                    <p>{moment(endDate).format('YYYY-MM-DD HH:mm')}</p>
                </div>
                {/*进度条*/}
                <div className={styles.listContentItem}>
                    {/*<Progress percent={80} status={status} strokeWidth={6} style={{width: 160}}/>*/}
                </div>
            </div>
        );
        // 题目条目
        getFieldDecorator('keys', {initialValue: questionContentList});
        const keys = getFieldValue('keys');
        const problemItems = keys.map((k, index) => {
            return (
                <FormItem label={`题目${index + 1}`} {...formLayout}>
                    {getFieldDecorator(`questionContent[${index}]`, {
                        rules: [{required: true, message: "输入题目"}],
                        initialValue: k.questionContent,
                        onChange:(e) => this.handleProblemChange(e,index)
                    })(
                        <TextArea placeholder="请输入至少五个字符" rows={3}/>
                    )}
                </FormItem>
            );
        });

        const getModalContent = () => {
            if (done) {
                return (
                    <Result
                        type="success"
                        title={this.state.msg}
                        actions={
                            <Button type="primary" onClick={this.handleDone}>
                                知道了
                            </Button>
                        }
                        className={styles.formResult}
                    />
                );
            }
            return (
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="期数" {...formLayout}>
                        {getFieldDecorator('taskNumber', {
                            rules: [{required: true, message: '请输入期数'}],
                            initialValue: current.taskNumber,
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="话题名称" {...formLayout}>
                        {getFieldDecorator('taskSubject', {
                            rules: [{required: true, message: '请输入话题名称'}],
                            initialValue: current.taskSubject,
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="开始时间" {...formLayout}>
                        {getFieldDecorator('beginDate', {
                            rules: [{required: false, message: '请选择开始时间'}],
                            initialValue: current.beginDate ? moment(current.beginDate,"YYYY-MM-DD HH:mm:ss") : null,
                        })(
                            <DatePicker
                                showTime
                                placeholder="请选择"
                                format="YYYY-MM-DD HH:mm:ss"
                                style={{width: '100%'}}
                            />
                        )}
                    </FormItem>
                    <FormItem label="截止时间" {...formLayout}>
                        {getFieldDecorator('endDate', {
                            rules: [{required: false, message: '请选择截止时间'}],
                            initialValue: current.endDate ? moment(current.endDate, "YYYY-MM-DD HH:mm:ss") : null,
                        })(
                            <DatePicker
                                showTime
                                placeholder="请选择"
                                format="YYYY-MM-DD HH:mm:ss"
                                style={{width: '100%'}}
                            />
                        )}
                    </FormItem>
                    <FormItem {...formLayout} label="话题描述">
                        {getFieldDecorator('subDescription', {
                            rules: [{message: '话题描述！'}],
                            initialValue: current.subDescription,
                        })(<TextArea rows={4}/>)}
                    </FormItem>
                    {problemItems}
                    <FormItem {...formLayout} label=" ">
                        <Button type="dashed" onClick={this.handleAddProblems} className={styles.addButton}>
                            <Icon type="plus"/> 添加题目
                        </Button>
                    </FormItem>
                </Form>
            );
        };
        return (
            <PageHeaderWrapper>
                <div className={styles.standardList}>
                    <Card
                        className={styles.listCard}
                        bordered={false}
                        title="话题列表"
                        style={{marginTop: 24}}
                        bodyStyle={{padding: '0 32px 40px 32px'}}
                        extra={extraContent}
                    >
                        <Button
                            type="dashed"
                            style={{width: '100%', marginBottom: 8}}
                            icon="plus"
                            onClick={this.showModal}
                            ref={component => {
                                /* eslint-disable */
                                this.addBtn = findDOMNode(component);
                                /* eslint-enable */
                            }}
                        >
                            发布话题
                        </Button>
                        <List
                            size="large"
                            rowKey="id"
                            loading={loading}
                            pagination={{onChange: (page) => this.handleChangePage(page),...pagination}}
                            dataSource={list}
                            renderItem={item => (
                                <List.Item
                                    actions={[
                                        <a
                                            onClick={e => {
                                                e.preventDefault();
                                                this.showEditModal(item);
                                            }}
                                        >
                                            编辑
                                        </a>,
                                        <Link to={"/work?taskId="+item.id}>
                                            提交
                                        </Link>,
                                        <Link
                                            to={"/task/commit?taskContentId="+item.id}
                                        >
                                            提交记录
                                        </Link>,
                                        // todo 按期数下载
                                        <a
                                            href={config.domain+"/bus/task-content/export"}
                                        >
                                            下载未提交名单
                                        </a>,
                                    ]}
                                >
                                    <List.Item.Meta
                                        title={<a href={item.href}>第{item.taskNumber}期</a>}
                                        description={item.taskSubject}
                                    />
                                    <ListContent data={item}/>
                                </List.Item>
                            )}
                        />
                    </Card>
                </div>
                <Modal
                    title={done ? null : `话题${current.id ? '编辑' : '添加'}`}
                    className={styles.standardListForm}
                    width={640}
                    bodyStyle={done ? {padding: '72px 0'} : {padding: '28px 0 0'}}
                    destroyOnClose
                    visible={visible}
                    {...modalFooter}
                >
                    {getModalContent()}
                </Modal>
            </PageHeaderWrapper>
        );
    }
}

export default TaskList;
